package com.ruoyi.common.mp.handle;/**
 * @InterfaceName: ListToStringHandle
 * @Description:
 * @Author: YourName
 * @Date: 2023-04-12
 */

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *@InterfaceName: ListToStringHandle
 *@Description:
 *@Author: lilirui
 *@Date: 2023-04-12
 */
@MappedTypes({List.class})
@Component
public class ListToStringHandle extends BaseTypeHandler<List> {


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
        if (!list.isEmpty()){
            preparedStatement.setString(i, JSON.toJSONString(list));
        }else {
            preparedStatement.setString(i,null);
        }

    }

    @Override
    public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        return result ==null? new ArrayList<>(): JSONArray.parseArray(result);
    }

    @Override
    public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        return result ==null? new ArrayList<>():JSONArray.parseArray(result);
    }

    @Override
    public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        return result ==null? new ArrayList<>():JSONArray.parseArray(result);
    }
}